package com.iseastar.guojiang.wallet;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;
import com.shouhuobao.take.weight.CircularImage;

import java.util.HashMap;

import droid.frame.activity.title.TitleRes;
import droid.frame.utils.GlideUtil;
import droid.frame.utils.android.MathUtils;

/**
 * Created by joker on 2018/1/17.
 * 火箭侠提现界面
 */
public class CourierTakeMoneyFromAccountActivity extends BaseActivity2 implements View.OnClickListener {

    private View mUnBindWXLayout;//未绑定微信布局
    private View mBindWXLayout;//绑定微信后的布局
    private CircularImage mWXHeadImageIV;//微信的头像
    private TextView mWXNameTV;//微信的名称
    private EditText mTakeMoneyET;//输入可提现的金额
    private TextView mCurrentReachMoneyTV;//实际到账的钱
    private TextView mTotalMoneyTV;//可提现的金额显示

    private TextView mWXTips;//微信是否绑定的提示语
    private TextView mOverTotalMoneyTipsTV;//超过总金额提示

    private String unBindWxTipStr = "绑定微信后，资金将直接提现至微信钱包-零钱";
    private String bindWxTipStr = "每周四进行提现审核，请在周三前提交提现申请";
    private String currentReachMoneyStr = "实际到账：¥%1$s元";
    private String totalMoneyStr = "可提现余额：¥%1$s元";
    private String totalMoney = "0";//总共金额
    private String takeMoney = "0";//提现的金额

    String mWXName = "";
    String mWxHeadImageUrl = "";
    String mOpenId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        AppHttp.getInstance().queryCourierWalletTakeMoneyInfo();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_courier_wallet_take_money);
        super.findViewById();
        getAppTitle().setCommonTitle("提现", new TitleRes("提现记录", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), WalletTakeMoneyHistoryActivity.class);
                intent.putExtra("openId", mOpenId);
                intent.putExtra("name", mWXName);
                intent.putExtra("headImgUrl", mWxHeadImageUrl);
                startActivityForResult(intent, 103);
            }
        }));
        //未绑定微信布局
        mUnBindWXLayout = findViewById(R.id.unbind_wx_ll);
        //立即绑定微信
        findViewById(R.id.bind_wx_tv).setOnClickListener(this);
        //绑定微信布局
        mBindWXLayout = findViewById(R.id.binded_wx_ll);
        mWXHeadImageIV = (CircularImage) findViewById(R.id.wx_head_iv);
        mWXNameTV = (TextView) findViewById(R.id.wx_name_tv);
        //更换账户
        findViewById(R.id.update_wx_account_tv).setOnClickListener(this);
        //提现
        findViewById(R.id.take_submit_TV).setOnClickListener(this);
        //客服电话拨打
        findViewById(R.id.client_phone_tv).setOnClickListener(this);
        //输入可提现的金额
        mTakeMoneyET = (EditText) findViewById(R.id.money_ET);
        mCurrentReachMoneyTV = (TextView) findViewById(R.id.current_reach_money_TV);
        mTotalMoneyTV = (TextView) findViewById(R.id.total_money_TV);
        //全部提现
        findViewById(R.id.take_total_money_TV).setOnClickListener(this);

        mWXTips = (TextView) findViewById(R.id.wx_tip_tv);
        mOverTotalMoneyTipsTV = (TextView) findViewById(R.id.over_total_money_tips_TV);
        mOverTotalMoneyTipsTV.setVisibility(View.INVISIBLE);

        mTakeMoneyET.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void afterTextChanged(Editable s) {
                if (Double.parseDouble(totalMoney) < 100) {
                    return;
                }
                if (isNotEmpty(s)) {
                    if (StringUtils.isNumber(s.toString())) {
                        if (Double.parseDouble(s.toString()) <= Double.parseDouble(totalMoney)) {
                            mOverTotalMoneyTipsTV.setVisibility(View.INVISIBLE);
                            if (Double.parseDouble(s.toString()) >= 100) {
                                takeMoney = (MathUtils.sub(s.toString(), 2)) + "";
                                mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, takeMoney));
                            } else {
                                mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                            }
                        } else {
                            mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                            mOverTotalMoneyTipsTV.setVisibility(View.VISIBLE);
                            mOverTotalMoneyTipsTV.setText("金额已超过可提现金额");
                        }
                    } else {
                        mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                        showToast("输入的金额有误");
                    }
                } else {
                    mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, "0"));
                    mOverTotalMoneyTipsTV.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //立即绑定微信
            case R.id.bind_wx_tv:
                intent = new Intent(getContext(), CourierBindWXActivity.class);
                startActivityForResult(intent, 101);
                break;
            //更换账户
            case R.id.update_wx_account_tv:
                intent = new Intent(getContext(), CourierBindWXActivity.class);
                intent.putExtra("name", mWXName);
                intent.putExtra("openId", mOpenId);
                intent.putExtra("headImageUrl", mWxHeadImageUrl);
                startActivityForResult(intent, 101);
                break;
            //全部提现
            case R.id.take_total_money_TV:
                if (Double.parseDouble(totalMoney) < 100) {
                    showToast("可提现金额最低为100元");
                    mOverTotalMoneyTipsTV.setVisibility(View.VISIBLE);
                    mOverTotalMoneyTipsTV.setText("金额已超过可提现金额");
                    return;
                }
                mTakeMoneyET.setText(totalMoney);
                mTakeMoneyET.setSelection(totalMoney.length());
                takeMoney = (MathUtils.sub(totalMoney, 2)) + "";
                mCurrentReachMoneyTV.setText(String.format(currentReachMoneyStr, takeMoney));
                break;
            //提现
            case R.id.take_submit_TV:
                if (isEmpty(mOpenId)) {
                    showToast("未绑定微信");
                    mOverTotalMoneyTipsTV.setVisibility(View.VISIBLE);
                    mOverTotalMoneyTipsTV.setText("未绑定微信");
                    return;
                }
                if (isEmpty(mTakeMoneyET.getText().toString())) {
                    showToast("请输入提现的金额");
                    return;
                }
                if (Double.parseDouble(totalMoney) < 100) {
                    if (Double.parseDouble(mTakeMoneyET.getText().toString()) <= Double.parseDouble(totalMoney)) {
                        showToast("最低提现金额为100元");
                        mOverTotalMoneyTipsTV.setVisibility(View.INVISIBLE);
                    } else {
                        showToast("金额已超过可提现金额");
                        mOverTotalMoneyTipsTV.setVisibility(View.VISIBLE);
                        mOverTotalMoneyTipsTV.setText("金额已超过可提现金额");
                    }
                    return;
                } else {
                    //判断总共的金额是否大于0
                    if (Double.parseDouble(totalMoney) < Double.parseDouble(mTakeMoneyET.getText().toString())) {
                        showToast("金额已超过可提现金额");
                        mOverTotalMoneyTipsTV.setVisibility(View.VISIBLE);
                        mOverTotalMoneyTipsTV.setText("金额已超过可提现金额");
                        return;
                    }
                    showLoadingDialog(null);
                    AppHttp.getInstance().courierWalletTakeMoneyFromAccount(mTakeMoneyET.getText().toString().trim());
                }
                break;
            //拨打客服电话
            case R.id.client_phone_tv:
                DialogMgr.showPhoneDialog(getContext(), null);
                break;

        }
    }

    /**
     * 设置绑定微信和未绑定微信view
     */
    private void updateWXStatusView() {
        if (isNotEmpty(mOpenId)) {
            mUnBindWXLayout.setVisibility(View.GONE);
            mBindWXLayout.setVisibility(View.VISIBLE);
            GlideUtil.loadImage(getContext(), mWxHeadImageUrl, 0, mWXHeadImageIV);
            mWXNameTV.setText(mWXName);
            mWXTips.setText(bindWxTipStr);
        } else {
            mWXTips.setText(unBindWxTipStr);
            mUnBindWXLayout.setVisibility(View.VISIBLE);
            mBindWXLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //查询账户信息
            case MsgID.query_courier_wallet_take_money_info:
                cancelLoadingDialog();
                ReqResult<Object> result = JSON.parserMap(msg.obj, Object.class);
                if (checkLoginStatus(result)) {
                    final HashMap<String, Object> map = result.getResultMap();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (map != null && map.size() > 0) {
                                mOpenId = map.get("openId") + "";
                                totalMoney = map.get("money") + "";
                                if (isNotEmpty(mOpenId)) {
                                    mWxHeadImageUrl = map.get("wxHeadImgUrl") + "";
                                    mWXName = map.get("wxAccountName") + "";
                                    mUnBindWXLayout.setVisibility(View.GONE);
                                    mBindWXLayout.setVisibility(View.VISIBLE);
                                    GlideUtil.loadImage(getContext(), mWxHeadImageUrl, 0, mWXHeadImageIV);
                                    mWXNameTV.setText(mWXName);
                                    mWXTips.setText(bindWxTipStr);
                                } else {
                                    mWXTips.setText(unBindWxTipStr);
                                    mUnBindWXLayout.setVisibility(View.VISIBLE);
                                    mBindWXLayout.setVisibility(View.GONE);
                                }
                                mTotalMoneyTV.setText(String.format(totalMoneyStr, totalMoney));
                            } else {
                                showToast("数据有误");
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            //提现数据返回
            case MsgID.courier_wallet_take_money_from_account:
                cancelLoadingDialog();
                ReqResult<?> reqResult = JSON.parser(msg.obj);
                if (checkLoginStatus(reqResult)) {
                    showToast("提现申请发起成功，系统每周四会进行提现审核哦！");
                    Intent intent = new Intent(getContext(), WalletTakeMoneyHistoryActivity.class);
                    intent.putExtra("openId", mOpenId);
                    intent.putExtra("name", mWXName);
                    intent.putExtra("headImgUrl", mWxHeadImageUrl);
                    startActivityForResult(intent, 102);
                } else {
                    showToast(reqResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == 101) {
            mWXName = data.getStringExtra("name");
            mWxHeadImageUrl = data.getStringExtra("headImageUrl");
            mOpenId = data.getStringExtra("openId");
            updateWXStatusView();
        } else if (resultCode == Activity.RESULT_OK && requestCode == 102) {
            Intent intent = new Intent();
            intent.putExtra("money", (MathUtils.sub(totalMoney, mTakeMoneyET.getText().toString())) + "");
            setResult(Activity.RESULT_OK, intent);
            finish();
        } else if (resultCode == Activity.RESULT_OK && requestCode == 103) {
            mWXName = data.getStringExtra("name");
            mWxHeadImageUrl = data.getStringExtra("headImageUrl");
            mOpenId = data.getStringExtra("openId");
            updateWXStatusView();
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
